<template>
  <BaseDialog
    v-model:visible="visible"
    title="编辑个人信息"
    icon="Edit"
    width="600px"
    :show-footer="false"
    :close-on-click-modal="false"
    @close="resetForm"
  >
    <div class="edit-profile-form">
      <!-- 头像上传区域 -->
      <div class="avatar-section">
        <div class="avatar-wrapper">
          <el-avatar :size="80" :src="getDisplayAvatar()">
            <el-icon><User /></el-icon>
          </el-avatar>
          
          <!-- 头像审核状态提示 -->
          <div v-if="avatarStatus.avatarStatus !== 'APPROVED'" class="avatar-status-badge">
            <el-tag 
              :type="getStatusTagType()" 
              size="small"
              effect="dark"
            >
              {{ avatarStatus.avatarStatusDesc }}
            </el-tag>
          </div>
          
          <div class="avatar-overlay" @click="triggerAvatarUpload">
            <el-icon><Camera /></el-icon>
            <span>更换头像</span>
          </div>
        </div>
        <input
          ref="avatarInput"
          type="file"
          accept="image/*"
          style="display: none"
          @change="handleAvatarChange"
        />
        <div class="avatar-tips">
          <el-text type="info" size="small">
            支持 JPG、PNG 格式，文件大小不超过 2MB
          </el-text>
          <br>
          <el-text type="info" size="small">
            <el-icon><Clock /></el-icon>
            为保障审核质量，24小时内最多允许更换3次头像
          </el-text>
          
          <!-- 审核状态说明 -->
          <div v-if="avatarStatus.avatarStatus === 'PENDING'" class="avatar-status-info">
            <el-text type="warning" size="small">
              <el-icon><Clock /></el-icon>
              头像正在审核中，审核通过后将自动更新
            </el-text>
          </div>
          
          <div v-if="avatarStatus.avatarStatus === 'REJECTED'" class="avatar-status-info">
            <el-text type="danger" size="small">
              <el-icon><WarningFilled /></el-icon>
              头像审核未通过：{{ avatarStatus.avatarRejectReason }}
            </el-text>
          </div>
        </div>
      </div>

      <!-- 个人信息表单 -->
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        @submit.prevent="handleSubmit"
      >
        <el-form-item label="昵称" prop="nickname">
          <BaseInput
            v-model="form.nickname"
            placeholder="请输入昵称"
            prefix-icon="User"
            size="large"
            maxlength="20"
            show-word-limit
            clearable
          />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <BaseInput
            v-model="form.email"
            type="email"
            placeholder="请输入邮箱"
            prefix-icon="Message"
            size="large"
            clearable
          />
          <div class="verification-status">
            <el-tag 
              :type="userStore.user?.emailVerified ? 'success' : 'warning'" 
              size="small"
            >
              {{ userStore.user?.emailVerified ? '已验证' : '未验证' }}
            </el-tag>
            <el-button 
              v-if="!userStore.user?.emailVerified" 
              type="text" 
              size="small" 
              :loading="sendingEmailVerification"
              @click="sendEmailVerification"
            >
              发送验证邮件
            </el-button>
          </div>
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <BaseInput
            v-model="form.phone"
            placeholder="请输入手机号"
            prefix-icon="Phone"
            size="large"
            maxlength="11"
            clearable
          />
          <div class="verification-status">
            <el-tag 
              :type="userStore.user?.phoneVerified ? 'success' : 'warning'" 
              size="small"
            >
              {{ userStore.user?.phoneVerified ? '已验证' : '未验证' }}
            </el-tag>
            <el-button 
              v-if="!userStore.user?.phoneVerified" 
              type="text" 
              size="small"
              :loading="sendingPhoneVerification"
              @click="sendPhoneVerification"
            >
              发送验证码
            </el-button>
          </div>
        </el-form-item>

        <el-form-item label="个人简介" prop="bio">
          <BaseInput
            v-model="form.bio"
            type="textarea"
            placeholder="介绍一下自己吧..."
            :rows="4"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <div class="form-actions">
        <BaseButton
          variant="outline"
          size="large"
          @click="visible = false"
        >
          取消
        </BaseButton>
        <BaseButton
          type="primary"
          size="large"
          :loading="saving"
          @click="handleSubmit"
        >
          保存
        </BaseButton>
      </div>
    </div>
  </BaseDialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '../../stores/user'
import { User, Camera, Clock, WarningFilled } from '@element-plus/icons-vue'
import BaseDialog from '../common/BaseDialog.vue'
import BaseInput from '../common/BaseInput.vue'
import BaseButton from '../common/BaseButton.vue'
import { upload, put, post, get } from '../../utils/api'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const userStore = useUserStore()
const formRef = ref()
const avatarInput = ref()
const saving = ref(false)
const sendingEmailVerification = ref(false)
const sendingPhoneVerification = ref(false)
const previewAvatar = ref('')
const avatarFile = ref(null)
const avatarStatus = ref({
  avatarUrl: '',
  avatarStatus: 'APPROVED',
  avatarStatusDesc: '已通过',
  avatarPendingUrl: '',
  avatarRejectReason: ''
})

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const form = reactive({
  nickname: '',
  email: '',
  phone: '',
  bio: ''
})

const rules = {
  nickname: [
    { max: 20, message: '昵称长度不能超过20个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^$|^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  bio: [
    { max: 200, message: '个人简介不能超过200个字符', trigger: 'blur' }
  ]
}

// 初始化表单数据
const initForm = () => {
  if (userStore.user) {
    form.nickname = userStore.user.nickname || ''
    form.email = userStore.user.email || ''
    form.phone = userStore.user.phone || ''
    form.bio = userStore.user.bio || ''
  }
}

// 监听用户数据变化
watch(() => userStore.user, initForm, { immediate: true })

// 获取头像状态
const fetchAvatarStatus = async () => {
  try {
    const response = await get('/user/avatar-status')
    if (response.data.code === 200) {
      avatarStatus.value = response.data.data
    }
  } catch (error) {
    console.error('获取头像状态失败:', error)
  }
}

// 获取显示的头像
const getDisplayAvatar = () => {
  // 如果有预览头像，显示预览
  if (previewAvatar.value) {
    return previewAvatar.value
  }
  
  // 如果头像状态是待审核，显示待审核头像
  if (avatarStatus.value.avatarStatus === 'PENDING' && avatarStatus.value.avatarPendingUrl) {
    return avatarStatus.value.avatarPendingUrl
  }
  
  // 否则显示正式头像
  return avatarStatus.value.avatarUrl || userStore.user?.avatarUrl
}

// 获取状态标签类型
const getStatusTagType = () => {
  switch (avatarStatus.value.avatarStatus) {
    case 'PENDING':
      return 'warning'
    case 'REJECTED':
      return 'danger'
    case 'APPROVED':
    default:
      return 'success'
  }
}

// 监听弹窗显示状态，获取头像状态
watch(visible, (newValue) => {
  if (newValue) {
    fetchAvatarStatus()
  }
})

// 触发头像上传
const triggerAvatarUpload = () => {
  avatarInput.value?.click()
}

// 处理头像文件选择
const handleAvatarChange = (event) => {
  const file = event.target.files[0]
  if (!file) return

  // 验证文件类型
  if (!['image/jpeg', 'image/png'].includes(file.type)) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
    return
  }

  // 验证文件大小
  if (file.size / 1024 / 1024 > 2) {
    ElMessage.error('头像大小不能超过 2MB!')
    return
  }

  avatarFile.value = file

  // 预览头像
  const reader = new FileReader()
  reader.onload = (e) => {
    previewAvatar.value = e.target.result
  }
  reader.readAsDataURL(file)
}

// 上传头像
const uploadAvatar = async () => {
  if (!avatarFile.value) return null

  try {
    const formData = new FormData()
    formData.append('avatar', avatarFile.value)

    console.log('正在上传头像:', {
      fileName: avatarFile.value.name,
      fileSize: avatarFile.value.size,
      fileType: avatarFile.value.type
    })

    // 使用专门的 upload 方法，确保正确处理 multipart/form-data
    const response = await upload('/user/upload-avatar', formData, {
      timeout: 60000, // 文件上传增加超时时间
      headers: {
        // 明确删除 Content-Type，让浏览器自动设置 multipart/form-data
        'Content-Type': undefined
      }
    })

    console.log('头像上传响应:', response)

    if (response.code === 200) {
      return response.data.avatarUrl
    } else {
      throw new Error(response.message || '上传头像失败')
    }
  } catch (error) {
    console.error('上传头像失败:', error) 
    
    // 更详细的错误处理
    let errorMessage = '上传头像失败'
    if (error.code === 'ECONNABORTED') {
      errorMessage = '上传超时，请检查网络连接'
    } else if (error.response?.status === 413) {
      errorMessage = '文件过大，请选择更小的图片'
    } else if (error.response?.status === 415) {
      errorMessage = '不支持的文件格式'
    } else if (error.response?.data?.message) {
      errorMessage = error.response.data.message
      // 特殊处理频率限制错误
      if (errorMessage.includes('头像更换过于频繁') || errorMessage.includes('24小时内最多允许更换3次')) {
        ElMessage({
          message: errorMessage,
          type: 'warning',
          duration: 8000, // 延长显示时间
          showClose: true
        })
        return null
      }
    } else if (error.message) {
      errorMessage = error.message
    }
    
    ElMessage.error(errorMessage)
    return null
  }
}

// 发送邮箱验证
const sendEmailVerification = async () => {
  try {
    sendingEmailVerification.value = true
    const response = await post('/user/send-email-verification', {})

    if (response.data.code === 200) {
      ElMessage.success('验证邮件已发送，请查收')
    } else {
      throw new Error(response.data.message || '发送失败')
    }
  } catch (error) {
    ElMessage.error('发送验证邮件失败: ' + (error.response?.data?.message || error.message))
  } finally {
    sendingEmailVerification.value = false
  }
}

// 发送手机验证
const sendPhoneVerification = async () => {
  try {
    sendingPhoneVerification.value = true
    const response = await post('/user/send-phone-verification', {})

    if (response.data.code === 200) {
      ElMessage.success('验证码已发送，请查收短信')
    } else {
      throw new Error(response.data.message || '发送失败')
    }
  } catch (error) {
    ElMessage.error('发送验证码失败: ' + (error.response?.data?.message || error.message))
  } finally {
    sendingPhoneVerification.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    saving.value = true

    // 先上传头像（如果有）
    let avatarUploaded = false
    if (avatarFile.value) {
      const avatarUrl = await uploadAvatar()
      if (avatarUrl) {
        avatarUploaded = true
        ElMessage.success('头像已提交审核，审核通过后将自动更新')
        // 刷新头像状态
        await fetchAvatarStatus()
      } else {
        saving.value = false
        return
      }
    }

    // 更新个人信息
    const updateData = { ...form }

    const response = await put('/user/profile', updateData)

    if (response.code === 200) {
      // 更新用户store中的信息
      await userStore.getCurrentUser()
      
      if (!avatarUploaded) {
        visible.value = false
        emit('success')
        ElMessage.success('个人信息更新成功')
      } else {
        ElMessage.success('个人信息更新成功，头像审核中')
      }
      resetForm()
    } else {
      throw new Error(response.message || '更新失败')
    }
  } catch (error) {
    console.error('保存用户信息失败:', error)
    ElMessage.error('更新个人信息失败: ' + (error.response?.data?.message || error.message))
  } finally {
    saving.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  initForm()
  previewAvatar.value = ''
  avatarFile.value = null
  if (avatarInput.value) {
    avatarInput.value.value = ''
  }
}
</script>

<style scoped>
.edit-profile-form {
  padding: 0;
  max-height: 100%;
  overflow: visible;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: var(--spacing-xl);
  padding-bottom: var(--spacing-xl);
  border-bottom: 1px solid var(--color-border-light);
}

.avatar-wrapper {
  position: relative;
  cursor: pointer;
  margin-bottom: var(--spacing-md);
}

.avatar-status-badge {
  position: absolute;
  top: -8px;
  right: -8px;
  z-index: 10;
}

.avatar-status-info {
  margin-top: var(--spacing-xs);
  padding: var(--spacing-xs);
  background: var(--color-bg-light);
  border-radius: var(--border-radius-sm);
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
}

.avatar-status-info .el-icon {
  font-size: 14px;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  opacity: 0;
  transition: var(--transition-fast);
  font-size: var(--font-size-xs);
  gap: var(--spacing-xs);
}

.avatar-wrapper:hover .avatar-overlay {
  opacity: 1;
}

.avatar-tips {
  text-align: center;
}

.verification-status {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: var(--spacing-xs);
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: var(--spacing-md);
  margin-top: var(--spacing-xl);
  padding-top: var(--spacing-lg);
  border-top: 1px solid var(--color-border-light);
}

/* 表单样式优化 */
:deep(.el-form-item__label) {
  font-weight: var(--font-weight-medium);
  color: var(--color-text-primary);
  margin-bottom: var(--spacing-sm);
}

/* 响应式设计 */
@media (max-width: 480px) {
  .verification-status {
    flex-direction: column;
    align-items: flex-start;
    gap: var(--spacing-xs);
  }
  
  .form-actions {
    flex-direction: column-reverse;
    gap: var(--spacing-sm);
  }
  
  .form-actions .base-button {
    width: 100%;
  }
}
</style>
